package cn.edu.nju.software.cdiy.action.user.all;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.cdiy.bean.User;
import cn.edu.nju.software.cdiy.service.UserService;
import cn.edu.nju.software.cdiy.util.BusinessConstant;
import cn.edu.nju.software.cdiy.util.Constant;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class RegisterAction extends ActionSupport implements SessionAware, ServletResponseAware {

	private Map<String, Object> session;
	private HttpServletResponse response;
	private UserService userService;
	private User user;
	private String authenticode;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
		this.response.setCharacterEncoding("UTF-8");
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setAuthenticode(String authenticode) {
		this.authenticode = authenticode;
	}

	public void register() throws Exception {
		String rightCode = (String) session.get(Constant.S_AUTHENTICODE);
		if (!rightCode.equals(authenticode)) {
			response.getWriter().write("验证码错误！");
			return;
		}
		user.setType(userService.getNormal());
		user.setState(userService.getActiveState());
		User newUser = userService.registor(user);
		if(newUser != null) {
			session.put(BusinessConstant.S_USER, newUser);
			response.getWriter().write("注册成功！");
		} else {
			response.getWriter().write("此用户名已存在！");
		}
	}
	
}
